package com.company.tree;

import com.company.TreeNode;
import sun.reflect.generics.tree.Tree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author jrue
 * @version 1.0
 * @date 2020/1/27 14:04
 * https://leetcode-cn.com/problems/binary-tree-level-order-traversal/
 * 给定一个二叉树，返回其按层次遍历的节点值。 （即逐层地，从左到右访问所有节点）。
 *
 * 例如:
 * 给定二叉树: [3,9,20,null,null,15,7],
 *
 *     3
 *    / \
 *   9  20
 *     /  \
 *    15   7
 * 返回其层次遍历结果：
 *
 * [
 *   [3],
 *   [9,20],
 *   [15,7]
 * ]
 */
public class BinaryTreeLevelOrderTraversal {

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> lists = new ArrayList<>();
        if (root == null) return lists;

        Queue<TreeNode> queue = new LinkedList<>();

        int preNodeCount = 1;
        int thisNodeCount = 0;

        queue.offer(root);
        List<Integer> data = new ArrayList<>();
        while (!queue.isEmpty()) {
            TreeNode thisNode = queue.poll();
            data.add(thisNode.val);
            preNodeCount--;

            if (thisNode.left != null) {
                thisNodeCount++;
                queue.offer(thisNode.left);
            }
            if (thisNode.right != null) {
                thisNodeCount++;
                queue.offer(thisNode.right);
            }

            if (preNodeCount == 0) {
                preNodeCount = thisNodeCount;
                thisNodeCount=0;
                lists.add(data);
                data = new ArrayList<>();
            }
        }
        return lists;
    }

}
